package com.app.basic.server.impl;

import com.app.basic.dao.entity.SysUser;
import com.app.basic.dao.mapper.SysUserMapper;
import com.app.basic.server.UserServiceFace;
import com.app.enums.RoleTypeEnum;
import com.app.execptions.MyRuntimeException;
import com.app.model.dto.LoginDTO;
import com.app.model.dto.RegisterDTO;
import com.app.security.JwtToken;
import com.app.security.JwtUtil;
import com.app.utils.CaptchaGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserServiceFaceImpl implements UserServiceFace {

    private final SysUserMapper sysUserMapper;


    @Override
    public Map<String, Object> login(LoginDTO loginDTO) {
        CaptchaGenerator.verification(loginDTO.getUuid(), loginDTO.getUserCode());
        if (!StringUtils.hasText(loginDTO.getUsername()) || !StringUtils.hasText(loginDTO.getPassword())) {
            throw new MyRuntimeException("账号密码不能为空");
        }

        Subject subject = SecurityUtils.getSubject();
        String token = JwtUtil.createJWT(loginDTO.getUsername(), "back" , "user" , Duration.ofDays(3).toMillis());
        JwtToken jwtToken = new JwtToken(token, loginDTO.getPassword());
        try {
            subject.login(jwtToken);
        } catch (UnknownAccountException e) {
            throw new MyRuntimeException("账号不存在");
        } catch (IncorrectCredentialsException e) {
            throw new MyRuntimeException("密码错误");
        }
        SysUser backUser = getUserByUsername(loginDTO.getUsername());
        Map<String, Object> map = new HashMap<>();
        map.put("user" , backUser);
        map.put("token" , token);
        map.put("role" , backUser.getRole());
        return map;
    }

    @Override
    public SysUser getUserByUsername(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getUsername, username);
        return sysUserMapper.selectOne(queryWrapper);
    }

    @Override
    public Object register(RegisterDTO registerDTO) {
        CaptchaGenerator.verification(registerDTO.getUuid(), registerDTO.getUserCode());
        String username = registerDTO.getUsername();
        String password = registerDTO.getPassword();
        String confirmPassword = registerDTO.getConfirmPassword();
        RoleTypeEnum roleTypeEnum = registerDTO.getRole();
        if (StringUtils.hasText(username)
                && StringUtils.hasText(password)
                && StringUtils.hasText(confirmPassword)
        ) {
            if (!confirmPassword.equals(password)) {
                throw new MyRuntimeException("两次密码不一致");
            }
            SysUser user = getUserByUsername(username);
            if (user != null) {
                throw new MyRuntimeException("用户名已存在换一个试试");
            }
            SysUser newUser = new SysUser();
            newUser.setUsername(username);
            newUser.setPassword(password);
            newUser.setRole(roleTypeEnum);
            return sysUserMapper.insert(newUser);
        } else {
            throw new MyRuntimeException("注册信息不完整");
        }

    }

    @Override
    public List<RoleTypeEnum> roles() {
        return Arrays.stream(RoleTypeEnum.values()).collect(Collectors.toList());
    }
}
